package com.fxkj.cloud.drms.ui.mqtt.handler;

import com.fxkj.cloud.dbs.common.model.response.MqttResponse;
import com.fxkj.common.utils.JacksonUtil;
import com.google.gson.reflect.TypeToken;
import io.netty.buffer.ByteBuf;

import java.util.regex.Matcher;

/**
 * <p>description: </p>
 * @author ww
 * @date 2025/3/17 10:58
 */
public abstract class AbstractReceiveHandler<T> {

    //这里使用了泛型,子类可以根据自己的需求,实现doHandler方法,进行处理,主要是为了统一解析,避免手动解析json,提高性能
    //这里使用了JacksonUtil,是为了避免手动解析json,提高性能
    void doHandler(Matcher matcher, String topic, ByteBuf payload) {
        byte[] msgBytes = new byte[payload.readableBytes()];
        payload.readBytes(msgBytes);
        T data = parseData(msgBytes);
        try {
            if (indexNum() > 1) {
                String[] dataStrs = new String[indexNum()];
                for (int i = 0; i < indexNum(); i++) {
                    dataStrs[i] = matcher.group(i + getIndex());
                }
                doHandler(topic, data, dataStrs);
            } else {
                doHandler(topic, data, matcher.group(getIndex()));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    //子类自己实现处理方法
    protected abstract void doHandler(String topic, T data, String... topicParams) throws Exception;

    protected Class<T> getClazz() {
        return null;
    }

    //默认解析方法
    protected T parseData(byte[] msgBytes) {
        if (getType() == null && getClazz() != null) {
            return JacksonUtil.fromBytes(msgBytes, getClazz());
        } else {
            return JacksonUtil.fromBytes(msgBytes, getType());
        }
    }

    protected int getIndex() {
        return 1;
    }

    protected int indexNum() {
        return 1;
    }

    protected com.fasterxml.jackson.core.type.TypeReference<T> getType() {
        return null;
    }
}
